﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DataBindingTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IObservable<ViewEvent>
    {
        public MyPresenter myPresenter { get; set; }
        private List<IObserver<ViewEvent>> eventSubscribers;
        public MainWindow()
        {
            eventSubscribers = new List<IObserver<ViewEvent>>();
            InitializeComponent();
            myPresenter = new MyPresenter(this);
        }

        public IDisposable Subscribe(IObserver<ViewEvent> observer)
        {
            eventSubscribers.Add(observer);
            return new eventUnsubscribe(eventSubscribers, observer);
        }

        private void event_handler(object sender, RoutedEventArgs e)
        {
            var _event = new ViewEvent(sender,e);
            foreach (var handler in eventSubscribers)
            {
                handler.OnNext(_event);
            }
        }

        private class eventUnsubscribe : IDisposable
        {
            
            private List<IObserver<ViewEvent>>_subscribers;
            private IObserver<ViewEvent> _subscriber;

            public eventUnsubscribe(List<IObserver<ViewEvent>> subscribers, IObserver<ViewEvent> subscriber)
            {
                this._subscribers = subscribers;
                this._subscriber = subscriber;
            }

            public void Dispose()
            {
                if (_subscriber != null && _subscribers.Contains(_subscriber))
                    _subscribers.Remove(_subscriber);
            }
        }
    }
}
